package item

import (
	"game_server/logic/db/api"
	"game_server/logic/db/handler"
	"game_server/logic/db/mark"
	. "game_server/logic/internal"
	"game_server/logic/item/model"
)

type itemDal struct {
}

func init() {
	dal := new(itemDal)
	Skeleton.AfterInit(func() {
		db_api.Register(dal)
	})
}

func (*itemDal) Name() string {
	return "item"
}

func (*itemDal) DBMark() db_mark.Enum {
	return db_mark.Item
}

func (*itemDal) OnSaveDB(session *db_handler.Session, args *db_handler.SaveArgs) (result *db_handler.SaveResult, errs []error) {
	player := args.Player
	for itemId, _ := range player.Item.Inserted {
		if item, exists := player.Item.Data[itemId]; exists {
			if _, err := session.Insert(item); err != nil {
				errs = append(errs, err)
			}
		}
	}

	for itemId, _ := range player.Item.Updated {
		if item, exists := player.Item.Data[itemId]; exists {
			_, err := session.Where("PlayerId = ? And Id = ?", item.PlayerId, item.Id).Update(item)
			if err != nil {
				errs = append(errs, err)
			}
		}
	}

	for itemId, _ := range player.Item.Deleted {
		item := item_model.NewItem(player.Id(), itemId)
		_, err := session.Where("PlayerId = ? And Id = ?", item.PlayerId, item.Id).Delete(item)
		if err != nil {
			errs = append(errs, err)
		}
	}

	return
}

func (*itemDal) OnLoadDB(session *db_handler.Session, args *db_handler.LoadArgs) (result *db_handler.LoadResult, err error) {
	player := args.Player
	playerId := player.Id()

	items := make([]*item_model.Item, 0)
	err = session.Where("PlayerId = ?", playerId).Find(&items)
	if err != nil {
		return
	}

	data := player.Item.Data
	for _, item := range items {
		data[item.Id] = item
	}

	return
}
